import { defineStore } from "pinia";

import { accoutLogin, getUserInfo, getMenuById } from "@/service/api/login";
import localCache from "@/utils/cache";
import router, { addRoutesWithMenu } from "@/router";
import { menuToPermission } from "@/utils/map-menu";

import useAllDataStore from "./all";
import { ElMessage } from "element-plus";

const useLoginStote = defineStore("login", {
  state: () => {
    return {
      token: "",
      userInfo: {},
      menus: [],
      permissions: [],
    };
  },
  actions: {
    async accoutLoginAction(payload) {
      const loginResult = await accoutLogin(payload);
      const { id, token } = loginResult.data;
      this.token = token;
      localCache.setItem("token", token);

      const userRes = await getUserInfo(id);
      const userInfo = userRes.data;
      this.userInfo = userInfo;
      localCache.setItem("userInfo", userInfo);

      // 根据用户角色获取菜单
      const menuResult = await getMenuById(userInfo.role.id);
      this.menus = menuResult.data;
      localCache.setItem("menuInfo", this.menus);

      //获取按钮权限
      const permission = menuToPermission(this.menus);
      this.permissions = permission;
      localCache.setItem("permissions", this.permissions);

      // 获取部门和角色
      const all = useAllDataStore();
      all.getAllDataList("department");
      all.getAllDataList("role");

      //路由添加
      addRoutesWithMenu(this.menus);

      router.push("/main");
    },
    loadLocalLogin() {
      this.token = localCache.getItem("token");
      this.userInfo = localCache.getItem("userInfo");
      this.menus = localCache.getItem("menuInfo");
      this.permissions = localCache.getItem("permissions");

      if (this.token && this.menus) {
        addRoutesWithMenu(this.menus);
      }
    },
    logoutLogin() {
      localCache.clearItem();
      router.push("/");
      // ElMessage({ message: "退出成功", type: "success" });
    },
  },
  getters: {},
});

export default useLoginStote;
